package com.itHsuSE.experiment;

/**
 * @author Hsu琛君珩
 * @version 1.0
 */
public class Experiment6_2 {
    public static void main(String[] args) {
        // 创建两个 RunnableDelayThread 对象
        RunnableDelayThread thread1 = new RunnableDelayThread();
        RunnableDelayThread thread2 = new RunnableDelayThread();

        // 创建线程对象并将其与 RunnableDelayThread 实例关联
        Thread t1 = new Thread(thread1);
        Thread t2 = new Thread(thread2);

        // 启动线程
        t1.start();
        t2.start();

        try {
            // 主线程休眠1秒，以确保线程有足够的时间执行
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // 处理可能发生的 InterruptedException
            System.out.println("线程异常");
        }
    }
}

class RunnableDelayThread implements Runnable {
    private static int count = 0;
    private int no;// 编号
    private int delay;// 延迟

    public RunnableDelayThread() {
        // 为每个线程分配一个唯一的编号
        count++;
        no = count;
    }

    @Override
    public void run() {
        try {
            // 模拟线程的行为，循环10次
            for (int i = 0; i < 10; i++) {
                // 生成随机的延迟时间
                delay = (int) (Math.random() * 5000);
                // 使线程休眠指定的延迟时间
                Thread.sleep(delay);
                // 打印线程编号和延迟时间
                System.out.println("Thread " + no + " with a delay " + delay);
            }
        } catch (InterruptedException e) {
            // 捕获并处理可能发生的 InterruptedException
        }
    }
}
